import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Button,
  Card,
  Table,
  Divider,
  Popconfirm,
  Spin,
  Badge,
  Modal,
  message,
} from 'antd';
import { routerRedux } from 'dva/router';
import Search from '../../components/Search';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import goodsService from '@/services/goods';
import CopyToClipboard from '@/components/CopyToClipboard';
import moment from 'moment';

const auditState = ['审核中', '审核拒绝', '审核通过'];
const tabList = [
  {
    key: '0',
    tab: '全部商品',
    prop: 'allCounts',
    filterKey: '',
    filterStatus: '',
  },
  {
    key: '1',
    tab: '审核通过',
    prop: 'putOnCounts',
    filterKey: 'type',
    filterStatus: '1',
  },
  {
    key: '2',
    tab: '审核拒绝',
    prop: 'notPutOnCounts',
    filterKey: 'type',
    filterStatus: '2',
  },
  {
    auditState: 3,
    key: '3',
    prop: 'pendingCounts',
    tab: '待审核',
    filterKey: 'auditState',
    filterStatus: '0',
  },
  {
    auditState: 4,
    prop: 'notPassCounts',
    key: '4',
    tab: '未通过',
    filterKey: 'auditState',
    filterStatus: '1',
  },
];

@connect(({ goodsList, loading }) => ({
  ...goodsList,
  loading: loading.models.goodsList,
}))
class List extends PureComponent {
  state = {
    tableData: [],
    AuditDetail: [],
    loading: true,
    tabType: '0',
    auditVisible: false,
    current: 1,
    pageNumber: 1,
    pageSize: 10,
    total: 0,
    counts: {},
    categories: [],
    modalTableCurrent: 1,
    modalPageSize: 10,
    modalTotal: 0,
    filter: {},
  };

  columns = [
    {
      title: '商品编号',
      dataIndex: 'productId',
      width: 120,
      align: 'center',
      render: text => <CopyToClipboard text={text} />,
    },
    {
      title: '商品图片',
      dataIndex: 'src',
      render: text => <img src={text} alt="" style={{ width: 60, height: 60 }} />,
    },
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '商品类目',
      dataIndex: 'opeCategoryStr',
      width: 160,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 90,
      key: 'status',
      render: text => {
        const success = text === 1;
        const status = success ? 'success' : 'default';
        const badgeText = success ? '已上架' : '已下架';
        return <Badge status={status} text={badgeText} />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 120,
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      key: 'auditState',
      width: 120,
      render: (text, record) => {
        const _text = auditState[text];
        return (
          <div>
            {_text}
            <br />
            {_text ? <a onClick={() => this.handleAuditModal(record)}>审核详情</a> : null}
          </div>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 120,
      render: (_, record) => (
        <div>
          <a onClick={() => this.gotoDetail(record.id)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleCopy(record)}>复制</a>
          <Divider type="vertical" />

          <Popconfirm title="是否删除该商品？" onConfirm={() => this.handleDelete(record)}>
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];

  auditColumns = [
    {
      title: '审核时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
    },
    {
      title: '审核人员',
      dataIndex: 'operator',
      width: 120,
    },
    {
      title: '审核结果',
      dataIndex: 'auditStatus',
      width: 120,
      render: text => {
        const _text = auditState[text];
        if (text === 1) {
          return (
            <span className="red">
              <Badge status="error" />
              未通过
            </span>
          );
        }
        return _text;
      },
    },
    {
      title: '反馈详情',
      dataIndex: 'feedBack',
    },
  ];

  componentWillMount() {
    this.initData();
    this.getTabCount();
    this.findCategories();
  }

  findCategories = () => {
    goodsService.findCategories().then(res => {
      this.setState({
        categories: res || [],
      });
    });
  };

  handleDelete = record => {
    goodsService
      .busDeleteProductBuyProductById({
        id: record.id,
      })
      .then(res => {
        message.success('删除成功');
        this.handleFilter();
      });
  };

  handleCopy = record => {
    goodsService
      .busCopyProductBuyProduct({
        productId: record.productId,
      })
      .then(res => {
        message.success('复制成功');
        this.handleFilter();
      });
  };

  gotoDetail = id => {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: `/goods/Purchase/PurchaseDetail/${id}`,
      }),
    );
  };

  handleUpDown = record => {
    const { dispatch, queryInfo } = this.props;
    dispatch({
      type: 'goodsList/busUpdateProductByUpOrDown',
      payload: record,
      callback: () => {
        this.setDispatch(queryInfo);
      },
    });
  };

  tabChange = type => {
    console.log(type);
    this.setState(
      {
        tabType: type,
      },
      () => {
        this.handleFilter();
      },
    );
  };

  handleAuditModal = record => {
    this.selectExamineProductAuditLog(record);
    this.setState({
      auditVisible: true,
    });
  };

  close = () => {
    this.setState({
      auditVisible: false,
    });
  };

  selectExamineProductAuditLog = record => {
    const { modalTableCurrent, modalPageSize } = this.state;
    goodsService
      .selectExamineProductAuditLog({
        id: record.id,
        itemId: record.productId,
        pageNumber: modalTableCurrent,
        pageSize: modalPageSize,
      })
      .then(res => {
        this.setState({
          AuditDetail: res.records || [],
          modalTotal: res.total,
          modalTableCurrent: res.current,
        });
      });
  };

  getTabCount = () => {
    goodsService.selectBusinessPrdouctCounts().then(res => {
      this.setState({
        counts: res,
      });
    });
  };

  initData = () => {
    const { pageNumber, pageSize, filter, tabType } = this.state;
    const item = tabList[tabType];
    if (item.filterKey) {
      filter[item.filterKey] = item.filterStatus
    }
    let payload = {
      pageNumber,
      pageSize,
      type: '1', // 默认已上架
      isDelete: false,
      ...filter,
    };
    this.setState(
      {
        loading: true,
      },
      () => {
        goodsService
          .selectBusinessDirectBuyPrdouct({
            ...payload,
          })
          .then(res => {
            message.success('获取信息成功');
            this.setState({
              tableData: res.records,
              total: res.total,
              loading: false,
              current: res.current,
            });
          });
      },
    );
  };

  handleFilter = (data = {}) => {
    if (data.queryType && data.queryType === '分页') {
      this.initData();
    } else {
      this.setState(
        {
          pageNumber: 1,
          pageSize: 10,
          filter: data,
        },
        () => {
          this.initData();
        },
      );
    }
  };

  //分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber: pageNumber,
      },
      () => {
        this.handleFilter({ queryType: '分页' });
      },
    );
  };

  showTotal = () => {
    return `共有${this.state.total}条`;
  };

  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState({ pageSize: pageSize }, () => {
      this.handleFilter({ queryType: '分页' });
    });
  };

  handleExportData = filter => {
    if (filter.createDate && filter.createDate.length > 1) {
      filter.createTimeStart = moment(filter.createDate[0]).format('YYYY-MM-DD HH:mm:ss');
      filter.createTimeEnd = moment(filter.createDate[1]).format('YYYY-MM-DD HH:mm:ss');
    }
    goodsService.exportBusinessDirectBuyPrdouct(filter).then(res => {
      // downloadFile(res)
      location.href = res;
    });
  };

  render() {
    const {
      loading,
      current,
      total,
      categories = [],
      tabType,
      auditVisible,
      AuditDetail,
      tableData,
      counts,
      modalPageSize,
      modalTotal,
      modalTableCurrent,
    } = this.state;
    const options = [{ field: 'categoryIds', options: categories }];

    return (
      <PageHeaderWrapper title={false} className="nav-tab">
        <Spin spinning={loading}>
          <Card bordered={false}>
            <Search
              needExport
              needReset
              source={'商品列表'}
              exportData={this.handleExportData}
              options={options}
              handleFilter={this.handleFilter}
            />
          </Card>
          <Card bordered={false}>
            <div className="ds-inline-block" onClick={() => this.gotoDetail('add')}>
              <Button type="primary">新增商品</Button>
            </div>
            <Table
              rowKey="id"
              columns={this.columns}
              dataSource={tableData}
              pagination={{
                current: current,
                total: total,
                onChange: this.onChange,
                showTotal: this.showTotal,
                showQuickJumper: true,
                pageSizeOptions: ['5', '10', '20'],
                showSizeChanger: true,
                onShowSizeChange: this.onShowSizeChange,
              }}
            />
          </Card>
        </Spin>
        <Modal
          title="审核详情"
          visible={auditVisible}
          footer={null}
          onCancel={this.close}
          width={900}
        >
          <Card bordered={false}>
            <Table
              rowKey="id"
              columns={this.auditColumns}
              dataSource={AuditDetail}
              pagination={{
                current: modalTableCurrent,
                total: modalTotal,
                onChange: this.onChange,
                showTotal: this.showTotal,
                showQuickJumper: true,
                pageSizeOptions: ['5', '10', '20'],
                showSizeChanger: true,
                onShowSizeChange: this.onShowSizeChange,
              }}
            />
          </Card>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default List;
